import DApp from '../config/configuration.js';
import BigNumber from "bignumber.js";
import detectEthereumProvider from "@metamask/detect-provider";
import { ethers } from "ethers";
import store from '@/utils/store.js'
const API = {
	// async getAddress() {
	// 	return new Promise(async (resolve, reject) => {
	// 		// 向用户发出权限 弹出钱包选择账户
	// 		let res = await window.ethereum.request({
	// 			"method": "wallet_requestPermissions",
	// 			"params": [{
	// 				"eth_accounts": {}
	// 			}]
	// 		}).catch((err) => {
	// 			// User rejected the request. （用户拒绝了请求。）
	// 			uni.showToast({
	// 				title: err.message,
	// 				icon: 'none'
	// 			});
	// 		});
	// 		if (res) {
	// 			// 2.账户选择完毕后，获取当前地址
	// 			var provider = await detectEthereumProvider();
	// 			let accounts = await provider.request({
	// 				method: "eth_requestAccounts"
	// 			}).catch((err) => {
	// 				uni.showToast({
	// 					title: err.message,
	// 					icon: 'none'
	// 				});
	// 			});
	// 			let address = accounts.length > 0 ? accounts[0] : '';
	// 			store.commit("setAddress", ethers.utils.getAddress(address))
	// 			resolve(ethers.utils.getAddress(address))
	// 		}
	// 	});
	// },
	async signer(message) { // 签名
		let {
			signer
		} = this.meta;
		let {
			account
		} = this;
		let res = await signer.signMessage(message)
		return res;
	},
	async balanceOf() { //查询余额
		let {
			balanceOf
		} = this.meta;
		let {
			account
		} = this;
		let res = await balanceOf(account)
		
		// 1. 返回bignumbner
		// return new BigNumber(res.toString())
		// return res
		
		// 2. 返回具体余额
		return res.div('1e18').toString()
		
		// const result = ethers.utils.formatEther(res)
		// const resultWithDecimals = (Math.floor(result * 10000) / 10000).toFixed(6); // 保留6位小数，不进行四舍五入
		// return resultWithDecimals
	},
	async transfer(to_address, amount) { //转账(对方地址，数量)
		const amountWei = ethers.utils.parseUnits(amount + '', 18)
		let {
			transfer
		} = this.meta;
		let {
			account
		} = this;
		// 估算 gas limit
		const estimatedGas = await this.meta.estimateGas.transfer(to_address, amountWei.toString());
		return new Promise((resolve, reject) => {
			transfer(to_address, amountWei.toString(),{
				gasLimit: new BigNumber(estimatedGas.toString()).times('1.5').toFixed(0)
			}).then(res => {
				resolve(res)
			}).catch(err => {
				uni.hideLoading();
				reject(err)
			})
		});
	},
	async approve(contract_address, amount) { //授权（合约地址，数量）
		const amountWei = ethers.utils.parseUnits(amount + '', 18)
		let {
			approve
		} = this.meta;
		let {
			account
		} = this;
		return new Promise((resolve, reject) => {
			approve(contract_address, amount).then(res => {
				resolve(res)
			}).catch(err => {
				uni.hideLoading();
				reject(err)
			})
		});
	},
	async allowance(address, contract_address) { //是否已授权(我的地址，合约地址)
		let {
			allowance
		} = this.meta;
		let {
			account
		} = this;
		return new Promise((resolve, reject) => {
			allowance(address, contract_address).then(res => {
				resolve(res)
			}).catch(err => {
				uni.hideLoading();
				reject(err)
			})
		});
	},
	async decimals() { //获取代币精度
		let {
			decimals
		} = this.meta;
		let {
			account
		} = this;
		return new Promise((resolve, reject) => {
			decimals().then(res => {
				// const result = ethers.utils.formatEther(res)
				// const resultWithDecimals = (Math.floor(result * 10000) / 10000).toFixed(6); // 保留6位小数，不进行四舍五入
				resolve(res.toString())
			}).catch(err => {
				uni.hideLoading();
				reject(err)
			})
		});
	},

}

export default {
	meta: null,
	account: null,
	web3: null,
	async init(coin) {
		let obj = await DApp.erc20Init(coin);
		let {
			meta,
			account,
			web3
		} = obj;
		this.meta = meta;
		this.account = account;
		this.web3 = web3;
		return this;
	},
	...API
}